package helper;

import play.Logger;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 获取本地ip的工具.
 */
public class LocalIpAddressHelper {

    /**
     * 获取本地ip地址，有可能会有多个地址, 若有多个网卡则会搜集多个网卡的ip地址
     */
    public static Set<InetAddress> resolveLocalAddresses() {
        Set<InetAddress> addrs = new HashSet<>();
        Enumeration<NetworkInterface> ns = null;
        try {
            ns = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            // ignored...
        }
        while (ns != null && ns.hasMoreElements()) {
            NetworkInterface n = ns.nextElement();
            Enumeration<InetAddress> is = n.getInetAddresses();
            while (is.hasMoreElements()) {
                InetAddress i = is.nextElement();
                if (!i.isLoopbackAddress() && i.isAnyLocalAddress() && !i.isLinkLocalAddress() && !i.isMulticastAddress()
                        && !isPrivateIp(i.getHostAddress())) {
                    addrs.add(i);
                }
            }
        }
        return addrs;
    }

    /**
     * 得到排序后的私有IP
     */
    public static List<InetAddress> getSortedPrivateIp() {
        Set<InetAddress> inetAddresses = resolveLocalAddresses();
        return inetAddresses.stream().sorted(Comparator.comparing(InetAddress::getHostAddress)).collect(Collectors.toList());
    }

    public static Set<String> resolveLocalIps() {
        Set<InetAddress> addrs = resolveLocalAddresses();
        Set<String> ret = new HashSet<String>();
        for (InetAddress addr : addrs) {
            ret.add(addr.getHostAddress());
        }
        return ret;
    }

    /**
     * 读取本地IP列表.
     */
    public static String getLocalIp() {
        Set<InetAddress> addrs = resolveLocalAddresses();
        if (addrs.size() > 0) {
            return addrs.stream().map(i -> i.getHostAddress())
                    .sorted().collect(Collectors.joining(" or "));
        }
        return null;
    }

    /**
     * 读取可用于设置的IP列表.
     * 取前5个字母相同
     */
    public static String getLocalIp(String filterIp) {
        String prefixIp = filterIp.substring(0, 5);
        Logger.info("LOG00080: prefixIp = " + prefixIp);
        Set<InetAddress> addrs = resolveLocalAddresses();
        if (addrs.size() > 0) {
            Optional<String> optionalIp = addrs.stream().map(i -> i.getHostAddress())
                    .filter(s -> s.startsWith(prefixIp))
                    .sorted().findFirst();
            if (optionalIp.isPresent()) {
                return optionalIp.get();
            }
        }
        return null;
    }

    /**
     * 读取可用于设置的IP列表.
     * 取前5个字母相同
     */
    public static String getPrivateIp(String filterIp) {
        Set<InetAddress> addrs = resolveLocalAddresses();
        if (addrs.size() > 0) {
            return addrs.stream().map(i -> i.getHostAddress())
                    .sorted().collect(Collectors.joining(" or "));
        }
        return null;
    }

    private static boolean isSpecialIp(String ip) {
        if (ip.contains(":")) return true;
        if (ip.startsWith("127.")) return true;
        if (ip.startsWith("169.254.")) return true;
        if (ip.equals("255.255.255.255")) return true;
        return false;
    }

    /**
     * 是否私有网段地址IP： 以 10或172.16或192.168开头
     */
    private static boolean isPrivateIp(String ip) {
        if (ip.contains(":")) return false;
        if (ip.startsWith("10.")) return true;
        if (ip.startsWith("172.16.")) return true;
        if (ip.equals("192.168.")) return true;
        return false;
    }
}
